<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <!-- 
  浅拷贝：拷贝前后对象中基本类型(null,undefined,number,string,boolean)互不影响
，引用类型互相影响
  赋值：拷贝前后对象相同，基本类型和引用类型互相影响
-->
  <script>
    function qCopy(obj) {
      var target = {};
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          target[key] = obj[key];
        }
      }
      return target;
    }
    function Caozuo(way) {
      let p = { name: 'zs', hobbies: ['sing'] };
      switch (way) {
        case 'qCopy':
          let p1 = qCopy(p);
          p1.name = 'ls';
          p1.hobbies[0] = 'dang';
          console.log('浅拷贝原对象p', p); //{name:'zs',hobbies:['dang']}  {name:'ls',hobbies:['dang']}
          break;
        case 'sCopy':
          let p2 = JSON.parse(JSON.stringify(p));
          p2.name = 'ls';
          p2.hobbies[0] = 'dang';
          console.log('深拷贝原对象p', p); //{name:'zs',hobbies:['sing']}  {name:'ls',hobbies:['dang']
          break;
        default:
          let p3 = p;
          p3.name = 'ls';
          p3.hobbies[0] = 'dang';
          console.log('赋值原对象p', p, p3); //{name:'ls',hobbies:['dang']}  {name:'ls',hobbies:['dang']
      }
    }
    Caozuo('qCopy');
    Caozuo('sCopy');
    Caozuo();
  </script>
</html>
